package com.xb.loan.cashier.biz.task.plat;

import com.xb.loan.cashier.biz.dao.bean.CashierChargeOrder;
import com.xb.loan.cashier.biz.service.CashierChargeOrderService;
import com.xb.loan.cashier.biz.task.BaseTask;
import com.xb.loan.cashier.biz.util.Configure;
import com.xb.loan.cashier.service.constant.ICashierEnumConst;
import com.xb.loan.fund.service.ICashChargeService;
import com.xb.loan.fund.service.bean.ChargeResultVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * 回推充值结果任务
 */
@Component(value="pushChargeTask")
@Scope(value="prototype")
public class PushChargeTask extends BaseTask {
    
    private static final Logger log = LoggerFactory.getLogger(PushChargeTask.class);
    
    @Autowired
    private CashierChargeOrderService cashierChargeOrderService;
    
    private CashierChargeOrder cashierChargeOrder;
    
    public void setCashierChargeOrder(CashierChargeOrder cashierChargeOrder) {
        this.cashierChargeOrder = cashierChargeOrder;
    }

    /**
     * 回推充值结果（存在并发情况）
     * 1.校验关键数据是否被篡改
     * 2.调用业务系统回推接口
     * 3.更新推送状态，如果失败查询当前推送状态，如果为已推送状态直接退出，否则记录错误日志
     *
     */
    @Override
	public void execute() {
        log.info("exceute 开始推送充值通知结果   "+cashierChargeOrder.toString());
        int res = 0;
        int pushCount = 0;
        int pushStatus = ICashierEnumConst.CashierChargeSendStatus.NOTSEND.getStatus();
        int maxPushCount = Configure.getIntValue("job.platpush.maxCount");
        log.info("execute maxPushCount="+maxPushCount+",pushCount="+cashierChargeOrder.getPushCount());
        if (cashierChargeOrder.getPushCount()>=0) {
            pushCount = cashierChargeOrderService.queryPushCount(cashierChargeOrder.getOrderId());
            if (pushCount==maxPushCount) {
                log.info("exceute 推送已达到"+maxPushCount+"次,不能再推送！");
                return;
            }
        }
        //回推前校验数据是否被手动篡改
        boolean r = cashierChargeOrderService.validate(cashierChargeOrder.getMoney(), cashierChargeOrder.getPlatId(), cashierChargeOrder.getUserId(), cashierChargeOrder.getOrderId(), cashierChargeOrder.getPartnerId(),cashierChargeOrder.getSign());
        if (!r) {
            log.info("execute 数据校验不通过 platId="+cashierChargeOrder.getPlatId()+",orderId="+cashierChargeOrder.getOrderId()+",userId="+cashierChargeOrder.getUserId());
            return;
        }
        try {
        	ICashChargeService cashChargeService = (ICashChargeService)ctx.getBean("cashChargeService");
        	ChargeResultVO chargeResultVO = this.convertObject(cashierChargeOrder);
            cashChargeService.chargeResult(chargeResultVO);//调用dubbo方法
            pushStatus = ICashierEnumConst.CashierChargeSendStatus.SENDED.getStatus();
            log.error("execute 充值订单"+cashierChargeOrder.getOrderId()+"调用充值回推接口成功");
        } catch (Exception e) {
            log.error("execute 充值订单"+cashierChargeOrder.getOrderId()+"调用充值回推接口异常",e);
            if (cashierChargeOrder.getPushCount()>=0) {
                res = cashierChargeOrderService.updatePushCount(cashierChargeOrder.getOrderId(),pushStatus, maxPushCount);
                if (res<=0) {
                    log.info("execute 充值订单"+cashierChargeOrder.getOrderId()+"记录推送失败次数失败");
                }else {
                    log.info("execute 充值订单"+cashierChargeOrder.getOrderId()+"记录推送失败次数成功");
                }
            }
        }
        pushCount = cashierChargeOrderService.queryPushCount(cashierChargeOrder.getOrderId());
        if (pushCount==maxPushCount && 
                pushStatus==ICashierEnumConst.CashierChargeSendStatus.NOTSEND.getStatus()) {//达到次数限制且没发送成功
            pushStatus = ICashierEnumConst.CashierChargeSendStatus.SENDFAIL.getStatus();
        }
        if (pushStatus!=ICashierEnumConst.CashierChargeSendStatus.NOTSEND.getStatus()) {
            res = cashierChargeOrderService.updatePushStatusByOrderId(null, null, cashierChargeOrder.getOrderId(), pushStatus);
            if (res>0) {
                log.info("execute 充值订单"+cashierChargeOrder.getOrderId()+"推送状态更新成功");
            }else {
                int tempStatus = cashierChargeOrderService.queryPushStatus(cashierChargeOrder.getOrderId(), null, null);
                if (pushStatus!=tempStatus) {
                    log.info("execute 更新推送状态失败 platId="+cashierChargeOrder.getPlatId()+",orderId="+cashierChargeOrder.getOrderId());
                }
            }
        }
        
	}
    
    /**
     * 内部对象转换为外部对象 
     * @param cco
     * @return
     * 2016-1-28 by zhaolijun
     */
    private ChargeResultVO convertObject(CashierChargeOrder cco){
        ChargeResultVO chargeResultVO = new ChargeResultVO();
        chargeResultVO.setChargeId(cco.getOrderId());
        chargeResultVO.setPlatId(cco.getPlatId());
        chargeResultVO.setUserId(cco.getUserId());
        chargeResultVO.setMoney(cco.getMoney());
        chargeResultVO.setReturnCode(cashierChargeOrderService.convertStatus(cco.getStatus()));
        chargeResultVO.setPayChannelType(cco.getPayChannelType());
        chargeResultVO.setForeignId(cco.getCashierOrderId());
        chargeResultVO.setDigitalSign(cashierChargeOrderService.encrypt(cco));
        return chargeResultVO;
    }
    
}
